#include "Window.h"
#include "Control.h"

bool Control::HitTest(vec2 pt)
{
	int left = pos.x.val;
	int top = pos.y.val;
	int right = pos.x.val + size.x.val;
	int bottom = pos.y.val + size.y.val;

	if (left < pt.x && right > pt.x)
	{
		if (top < pt.y && bottom > pt.y)
		{
			return true;
		}
	}
	return false;
}

bool Control::SetAttribute(const char* attrName, const char* attrVal)
{
	if (strcmp(attrName, "pos") == 0)
	{
		int x, y;
		sscanf_s(attrVal, "%d,%d", &x, &y);
		pos.x = x;
		pos.y = y;
		return true;
	}
	else if (strcmp(attrName, "name") == 0)
	{
		this->name = attrVal;
		return true;
	}
	else if (strcmp(attrName, "size") == 0)
	{
		int w, h;
		sscanf_s(attrVal, "%d,%d", &w, &h);
		size.x = w;
		size.y = h;
		return true;
	}
	else if (strcmp(attrName, "margin") == 0)
	{
		int l, t, r, b;
		sscanf_s(attrVal, "%d,%d", &l, &t, &r, &b);
		margin.x = l;
		margin.y = t;
		margin.z = r;
		margin.w = b;
		return true;
	}
	else if (strcmp(attrName, "border") == 0)
	{
		int l, t, r, b;
		sscanf_s(attrVal, "%d,%d", &l, &t, &r, &b);
		border.x = l;
		border.y = t;
		border.z = r;
		border.w = b;
		return true;
	}
	else if (strcmp(attrName, "halign") == 0)
	{
		halign = FromHorizenAlignStr(attrVal);
		return true;
	}
	else if (strcmp(attrName, "valign") == 0)
	{
		valign = FromVerticalAlignStr(attrVal);
		return true;
	}
	else if (strcmp(attrName, "visible") == 0)
	{
		std::string strVal = std::string(attrVal);
		ToLowerStr(strVal);
		if (strcmp(strVal.data(), "false") == 0) {
			bVisible = false;
		}
		else {
			this->bVisible = true;
		}
		return true;
	}

	return false;
}

void Control::DoParseXmlElement(TiXmlElement* ele)
{
	ParseXmlElement(ele);
	if (name.val != "" && rootWindow != nullptr) {
		tstring ctrlName = name.val.data();
		rootWindow->PushNamedCtrl(ctrlName, this);
	}
}

Control* Control::GetHitControl(int x, int y)
{
	if (childs.size() == 0) {
		if (HitTest(vec2(x, y))) {
			return this;
		}
		else {
			return nullptr;
		}
	}
	if (childs.size() > 0) {
		Control* ctrl = nullptr;
		for (int i = 0; i < childs.size(); i++) {
			ctrl = childs[i].second->GetHitControl(x,y);
			if (ctrl != nullptr) {
				return ctrl;
			}
		}
		if (HitTest(vec2(x, y))) {
			return this;
		}
		return nullptr;
	}
	return nullptr;
}

BlueprintScriptLibrary::Class* Control::GetClass()
{
	static BlueprintScriptLibrary::Class* c = NewObj<BlueprintScriptLibrary::Class>();
	c->className = "Control";
	return c;

}

void Control::DrawBorder()
{
	glEnable(GL_FILL);
	glColor3f(0.5, 0.5, 0.5);
	if (bFocused)
	{
		glEnable(GL_FILL);
		glColor3f(0.2, 0.2, 0.2);
		glBegin(GL_QUADS);

	}
	else
	{
		glDisable(GL_FILL);
		glBegin(GL_LINE_LOOP);
	}

	glVertex3f(pos.x.val, pos.y.val, zIndex.val);
	glVertex3f(pos.x.val + size.x.val, pos.y.val, zIndex.val);
	glVertex3f(pos.x.val + size.x.val, pos.y.val + size.y.val, zIndex.val);
	glVertex3f(pos.x.val, pos.y.val + size.y.val, zIndex.val);
	glEnd();

}

